<?php
/**
 * 固定传播预算
 * @author qianxun
 *
 */
class SpreadBudget extends MY_Controller{
    function SpreadBudget(){
        parent::MY_Controller();
    }
    /**
     * 申请列表
     */
    function storeList(){
        if ($this->user['userRole'] != 1){
            showError('您无权限进去此页面');
        }
        //面包屑
        $this->viewData['breadcrumb'][] = array('url'=>'','title'=>'固定传播基金申请列表');
        
        //载入模型
        $this->load->model('spreadProcessModel');
        //年份
        $year = $this->input->get('year');
        $year || $year = $this->config->item('nowYear');
        $this->viewData['year'] = $year;
        $where = array();
        //专营店ID条件
        $where['storeId'] = array('in', $this->userLib->getViewStoreIds());
        //年份条件
        $where['year'] = $year;
        //固定传播基金金额汇总
        $procList = $this->spreadProcessModel->getNewList($where);
        foreach ($procList as $k => $v){
            if ($v['id'] != $v['belongProcId']){
                $belogProcData = $this->spreadProcessModel->getNewData($v['belongProcId']);
                $v['auditRoleStr'] = $belogProcData['auditRoleStr'];
                $v['auditRsStr'] = $belogProcData['auditRsStr'];
            }
            $procList[$k] = $v;
        }
        $this->viewData['procList'] = $procList; 
        
        $this->load->view('SpreadBudget/storeList', $this->viewData);
    }
    /**
     * 新增申请
     */
    function storeAdd(){
        $this->load->model('spreadProcessModel');
        $this->load->model('spreadProjectModel');
        $this->load->model('spreadProcStoreModel');
        if ($_POST){
            $procId = (int)$this->input->post('procId');
            $procId || showError('非法参数');
            //已选专营店列表
            $storeList = $this->input->post('storeList');
            //申报总金额
            $totalApplyMoney = 0;  
            foreach ((array)$storeList as $v){
                $totalApplyMoney += $v['applyMoney'];
            }
            //项目合同总金额
            $projectSumMoney = $this->spreadProjectModel->getSum(array('procId'=>$procId),'applyMoney');
            $projectSumMoney == $totalApplyMoney || showError('申报金额和合同金额必须一致');
            $procData = $this->spreadProcessModel->getData($procId);
            if ($this->spreadProcessModel->edit(array('storeId'=>$this->user['userId'],'id'=>$procId), array('auditRs'=>0,'auditRole'=>0,'storeList'=>serialize($storeList)))){
                //批量插入专营店数据,并默认审核状态为待审核状态
                $this->spreadProcStoreModel->del(array('procId'=>$procId),'*');
                foreach ($storeList as $k => $v){
                    $this->spreadProcStoreModel->add(array(
                        'procId' => $procId,
                        'storeType' => $this->user['userId'] == $k ? 1 : 2,
                        'storeId' => $k,
                        'storeName' => $v['storeName'],
                        'yearMoney' => (float)$v['yearMoney'],
                        'applyMoney' => (float)$v['applyMoney'],
                        'auditRole' => 0,
                        'auditRs' => 0,
                        'createTime' => time(),
                    ));
                    /* if ($this->user['userId'] != $k){
                        $id = $this->spreadProcessModel->initData(array(
                            'storeId' =>$k,
                            'year' => $procData['year'],
                            'belongProcId' => $procId,
                            'lostMoney' => serialize(array()),
                            'createTime' => time(),
                        ));
                        $this->spreadProcessModel->updateMoney($id);
                    } */
                }
                //投放项目默认待审核
                $this->spreadProjectModel->edit(array('storeId'=>$this->user['userId'],'procId'=>$procId), array('auditRs'=>0));
                $this->spreadProcessModel->updateMoney($procId);
                showSuccess('提交成功', printUrl('SpreadBudget', 'storeList'));
            }else{
                showError('提交失败');
            }
            
        }else{
            $procId = (int)$this->input->get('procId');
            if (!$procId){
                $year = (int)$this->input->get('year');
                $year || $year = $this->config->item('nowYear');
                $where = array(
                    'storeId' =>$this->user['userId'],
                    'year' => $year,
                );
                if (!$this->auth->isSpreadBudgetAdd(array_merge($where, array('timeUnit'=>0)))){
                    showError('您无权限申报');
                }
                $data = array(
                    'storeList' => serialize(array()),
                    'lostMoney' => serialize(array()),
                    'createTime' => time(),
                );
                $procId = $this->spreadProcessModel->upset($where, $data);
                $this->spreadProcessModel->edit(array('id'=>$procId,'belongProcId'=>0), array('belongProcId'=>$procId));
                //更新汇总金额
                $this->spreadProcessModel->updateMoney($procId);
                redirect(printUrl('SpreadBudget', 'storeAdd', array('procId'=>$procId)));
            }
            //主线流程数据
            $procData = $this->spreadProcessModel->getData($procId);
            if (!$this->auth->isSpreadBudgetEdit($procData)){
                showError('您无权限申报');
            }
            $this->viewData['procData'] = $procData;
            //面包屑
            $this->viewData['breadcrumb'][] = array('url'=>printUrl('SpreadBudget', 'storeList'),'title'=>'固定传播基金申请列表');
            if ($procId){
                $this->viewData['breadcrumb'][] = array('url'=>'','title'=>'修改申请');
            }else{
                $this->viewData['breadcrumb'][] = array('url'=>'','title'=>'新增申请');
            }
            //可选专营店列表
            $storeList = $this->spreadProcStoreModel->getStoreList($this->user['userId'], $procId);
            $this->viewData['storeList'] = $storeList;
            
            $this->load->view('SpreadBudget/storeAdd', $this->viewData);
        }
    }
    /**
     * 项目删除
     */
    function storeDel(){
        $procId = (int)$this->input->post('procId');
        $procId || showError('请选择要删除的固定传播基金申请');
        
        $this->load->model('spreadProcessModel');
        $procData = $this->spreadProcessModel->getData(array('id'=>$procId,'storeId'=>$this->user['userId']));
        if (!$this->auth->isSpreadBudgetDel($procData)){
            showError('您无权限删除此项目');
        }
        if ($this->spreadProcessModel->del($procId)){
            $this->load->model('spreadProjectModel');
            $this->spreadProjectModel->del(array('procId'=>$procId,'storeId'=>$this->user['userId']));
            $this->load->model('spreadProcStoreModel');
            $this->spreadProcStoreModel->del(array('procId'=>$procId), '*');
            showSuccess('删除固定传播基金成功');
        }else{
            showError('删除固定传播基金失败');
        }
    }
    /**
     * 投放类型新增编辑
     */
    function storeProjectAdd(){
        $this->load->model('spreadProcessModel');
        $this->load->model('spreadProjectModel');
        if ($_POST){
            $id = $this->input->get('projectId');
            $data = array(
                'storeId' => $this->user['userId'],
                'year' => date('Y'),
                'timeUnit' => 0,
                'procId' => (int)$this->input->post('procId'),
                'mediaType' => $this->input->post('mediaType'),
                'mediaTypeAlias' => $this->input->post('mediaTypeAlias'),
                'mediaSize' => $this->input->post('mediaSize'),
                'address' => $this->input->post('address'),
                'contractStart' => $this->input->post('startTime'),
                'contractEnd' => $this->input->post('endTime'),
                'remark' => $this->input->post('remark'),
                'contractFile' => (int)$this->input->post('contractFile'),
                'invoiceFile' => (int)$this->input->post('invoiceFile'),
                'auditTable' => (array)$this->input->post('auditTable'),
                'applyMoney' => (float)$this->input->post('applyMoney'),
                'auditRole' => 0,
                'auditRs' => 0
            );
            $data['procId'] || showError('请选择主线流程');
            $data['mediaType'] || showError('请选择投放类型');
            if($data['mediaType'] == -1 && !$data['mediaTypeAlias']){
                showError('请输入其他投放类型');
            }
            $data['mediaSize'] || showError('请输入投放规格');
            $data['contractStart'] || showError('请选择合同开始时间');
            $data['contractEnd'] || showError('请选择合同结束时间');
            strtotime($data['contractStart']) < strtotime($data['contractEnd']) || showError('合同开始时间必须小于合同结束时间');
            strtotime($data['contractEnd']) - strtotime($data['contractStart']) >= 86400*30*5 || showError('合同起止时间必须大于6个月');
            //合同附件数据
            $this->load->model('fileModel');
            $data['contractFile'] = $this->fileModel->getData( array('id'=>$data['contractFile']));
            $data['contractFile'] || showError('请上传合同附件');
            $data['contractFile'] = serialize($data['contractFile']);
            //发票附件数据
            if ($data['invoiceFile']){
                $data['invoiceFile'] = $this->fileModel->getData(array('id'=>$data['invoiceFile']));
            }else{
                $data['invoiceFile'] = array();
            }
            $data['invoiceFile'] || showError('请上传发票附件');
            $data['invoiceFile'] = serialize($data['invoiceFile']);
            //会签审批表
            $data['auditTable'] = $this->fileModel->getList(array('id'=>array('in',$data['auditTable'])));
            (count($data['auditTable']) > 0 && count($data['auditTable']) <= 3) || showError('会签审批表至少上传1张，最多可上传3张');
            $data['auditTable'] = serialize($data['auditTable']);
            
            $data['applyMoney'] || showError('请输入合同费用');
            if ($id){
                $rs = $this->spreadProjectModel->edit($id, $data);
            }else{
                $data['createTime'] = time();
                $rs = $this->spreadProjectModel->add($data);
            }
            if ($rs){
                showSuccess('保存成功', printUrl('SpreadBudget', 'storeList'));
            }else{
                showError('保存失败');
            }
        }else{
            $procId = (int)$this->input->get('procId');
            $projectData = array();
            $projectId = (int)$this->input->get('projectId');
            if($projectId){
                $projectData = $this->spreadProjectModel->getNewData($projectId);
                $projectData['auditTable'] = array_values((array)$projectData['auditTable']);
                $procId = (int)$projectData['procId'];
            }
            $procData = $this->spreadProcessModel->getData($procId);
            $this->viewData['procData'] = $procData;
            $this->viewData['projectData'] = $projectData;
            $this->viewData['action'] = 'edit';
            $this->load->view('SpreadBudget/storeProjectAdd', $this->viewData);
        }
    }
    /**
     * 投放类型删除
     */
    function storeProjectDel(){
        $projectId = (int)$this->input->post('projectId');
        $projectId || showError('请选择要删除的固定传播基金申请');
        
        $this->load->model('spreadProjectModel');
        $projectData = $this->spreadProjectModel->getData(array('id'=>$projectId,'storeId'=>$this->user['userId']));
        //主线流程数据
        $this->load->model('spreadProcessModel');
        $procData = $this->spreadProcessModel->getData(array('id'=>$projectData['procId'],'storeId'=>$this->user['userId']));
        if (!$this->auth->isSpreadBudgetDel($procData)){
            showError('您无权限删除此项目');
        }
        if ($this->spreadProjectModel->del($projectId)){
            $this->load->model('spreadProItemModel');
            $this->spreadProItemModel->del(array('projectId'=>$projectId), '*');
            showSuccess('删除投放类型成功');
        }else{
            showError('删除投放类型失败');
        }
    }
    /**
     * 返回投放类型列表HTML
     */
    function storeProjectList(){
        $procId = (int)$this->input->get('procId');
        $projectList = array();
        if ($procId ){
            $this->load->model('spreadProjectModel');
            $projectList = $this->spreadProjectModel->getNewList(array('storeId'=>$this->user['userId'],'procId'=>$procId));
        }
        $this->viewData['projectList'] = $projectList;
        $this->load->view('SpreadBudget/storeProjectList',$this->viewData);
    }
    /**
     * 返回指定投放类型相册
     */
    function storeProjectPhotos(){
        $projectId = (int)$this->input->get('projectId');
        $data = array(
            'title' => '会签审批表查看',
            'id' => $projectId,
            'start' => 0,
            'data' => array(),
        );
        if ($projectId){
            $this->load->model('spreadProjectModel');
            $projectData = $this->spreadProjectModel->getNewData($projectId);
            if ($projectData['auditTable']){
                foreach ((array)$projectData['auditTable'] as $v){
                    $data['data'][] = array(
                        'alert' => $v['origName'],
                        'pid' => $v['id'],
                        'src' => $v['viewPath'],
                        'thumb' => $v['viewPath'],
                    );
                }
            }
        }
        
        echo jsonEncode($data);
    }
    /**
     * 获取合同总金额
     */
    function getStoreProjectApplyMoney(){
        $sum = 0;
        $procId = (int)$this->input->get('procId');
        if ($procId){
            $this->load->model('spreadProjectModel');
            $sum = $this->spreadProjectModel->getSum(array('procId'=>$procId),'applyMoney');
        }
        echo $sum;
    }
    /**
     * 管理端列表
     */
    function adminList(){
        if ($this->user['userRole'] == 1){
            showError('您无权限进去此页面');
        }
        //面包屑
        $this->viewData['breadcrumb'][] = array('url'=>'','title'=>'固定传播基金管理');
        //载入模型
        $this->load->model('spreadProcessModel');
        $this->load->model('sellpointModel');
        //查询条件
        $where = array('auditRs >=' => 0);
        //专营店筛选
        $area = $this->input->get('area');
        $this->viewData['area'] = $area;
        $region = $this->input->get('region');
        $this->viewData['region'] = $region;
        $spsarea = $this->input->get('spsarea');
        $this->viewData['spsarea'] = $spsarea;
        $province = $this->input->get('province');
        $this->viewData['province'] = $province;
        $city = $this->input->get('city');
        $this->viewData['city'] = $city;
        $storeId = (int)$this->input->get('storeId');
        $this->viewData['storeId'] = $storeId;
        $keyword = $this->input->get('keyword');
        $this->viewData['keyword'] = $keyword;
        //查找对应地区列表
        $placeStoreList = $this->sellpointModel->searchStore($area, $region, $spsarea, $province, $city, $storeId, $keyword);
        $placeStoreIds = array_keys($placeStoreList);
        $this->viewData['allStoreList'] = $placeStoreList;
        //权限内专营店列表
        $viewStoreIds = $this->userLib->getViewStoreIds();
        if ($viewStoreIds == '*'){
            $where['storeId'] = array('in', $placeStoreIds);
        }else{
            $where['storeId'] = array('in', array_intersect($viewStoreIds, $placeStoreIds));
        }
        //年份
        $year = $this->input->get('year');
        $year || $year = $this->config->item('nowYear');
        $this->viewData['year'] = $year;
        //时间单位
        $this->viewData['timeUnit'] = (int)$this->input->get('timeUnit');
        $this->viewData['timeUnit'] && $where['timeUnit'] = $this->viewData['timeUnit'];
        //年份条件
        $where['year'] = $year;
        //$where['budgetApply > '] =0;
        $count = $this->spreadProcessModel->getCount($where);
        //分页
        $this->load->library('pagination');
        $getParam = $_GET;
        unset($getParam['c'], $getParam['m'], $getParam['page']);
        $config['base_url'] = printUrl($_GET['c'], $_GET['m'], $getParam);
        $config['total_rows'] = $count;
        $this->pagination->initialize($config);
        $this->viewData['pager'] = $this->pagination->create_links();
        $page = (int)$this->input->get('page');
        $limit = $this->pagination->per_page;
        
        $procList = $this->spreadProcessModel->getNewList($where, $limit, $page, '', 'belongProcId desc');
        foreach ($procList as $k => $v){
            if ($v['id'] != $v['belongProcId']){
                $belogProcData = $this->spreadProcessModel->getNewData($v['belongProcId']);
                $v['auditRoleStr'] = $belogProcData['auditRoleStr'];
                $v['auditRsStr'] = $belogProcData['auditRsStr'];
            }
            $procList[$k] = $v;
        }
        $this->viewData['procList'] = $procList;
        $this->load->view('SpreadBudget/adminList', $this->viewData);
    }
    /**
     * 预算审核
     */
    function adminAudit(){
        $this->load->model('spreadProcessModel');
        $this->load->model('spreadProcStoreModel');
        $this->load->model('spreadProjectModel');
        if ($_POST){
            $procId = (int)$this->input->post('procId');
            $procId || showError('请选择要审核的固定传播基金');
            $auditData = $this->input->post('audit');
            //提交类型
            $subtype = (int)$this->input->post('subtype');
            
            $auditRs = $this->spreadProcessModel->audit($procId, $auditData, $this->user);
            $jumpUrl = printUrl('SpreadBudget','adminList');
            if($auditRs){
                if ($subtype == 1){//如果继续审核下一家专营店
                    //审核下一个专营店
                    $where = array('auditRs' => 0);
                    //权限内专营店列表
                    $viewStoreIds = $this->userLib->getViewStoreIds();
                    if ($viewStoreIds == '*'){
                    
                    }else{
                        $where['storeId'] = array('in', $viewStoreIds);
                    }
                    $nextProcData = $this->spreadProcessModel->getList($where, 1, 0, '', 'belongProcId desc');
                    $nextProcData = array_values($nextProcData);
                    if ($nextProcData){
                        $jumpUrl = printUrl('SpreadBudget', 'adminAudit', array('procId'=>$nextProcData[0]['id']));
                    }
                }
                showSuccess('审核成功', $jumpUrl);
            }else{
                showError('审核失败');
            }
        }else{
            $procId = (int)$this->input->get('procId');
            $procId || showError('请选择要审核的固定传播基金');
            //面包屑
            $this->viewData['breadcrumb'][] = array('url'=>$_SERVER['HTTP_REFERER'],'title'=>'固定传播基金管理列表');
            $this->viewData['breadcrumb'][] = array('url'=>'','title'=>'固定传播基金申请审核');
            //项目数据
            $procData = $this->spreadProcessModel->getNewData($procId);
            if (!$this->auth->isSpreadBudgetAudit($procData)){
                showError('您无权限审核此项目');
            }
            $this->viewData['procData'] = $procData;
            //专营店数据
            $this->load->model('sellpointModel');
            $this->viewData['storeData'] = $this->sellpointModel->getStoreIdData($procData['storeId']);
            $procId = $procData['belongProcId'];
            //已选专营店列表
            $storeList = $this->spreadProcStoreModel->getList(array('procId'=>$procId));
            $this->viewData['storeList'] = $storeList;
            //投放类型列表
            $projectList = $this->spreadProjectModel->getNewList(array('procId'=>$procId));
            $this->viewData['projectList'] = $projectList;
            //项目合同总金额
            $projectSumMoney = $this->spreadProjectModel->getSum(array('procId'=>$procId),'applyMoney');
            $this->viewData['projectSumMoney'] = $projectSumMoney;
            //审核日志
            $this->load->model('auditLogModel');
            $this->viewData['auditList'] = $this->auditLogModel->getLogs(51, $procId);
            $this->viewData['auditData'] = $this->auditLogModel->getLastLog(51, $procId);
            //操作
            $this->viewData['action'] = 'audit';
            $this->load->view('SpreadBudget/adminAudit', $this->viewData);
        }
    }
    /**
     * 查看
     */
    function check(){
        $procId = (int)$this->input->get('procId');
        $procId || showError('请选择要查看的固定传播基金申请');
        //面包屑
        if ($this->user['userRole'] == 1){
            $this->viewData['breadcrumb'][] = array('url'=>printUrl('SpreadBudget', 'storeList'),'title'=>'固定传播基金申请列表 ');
        }else{
            $this->viewData['breadcrumb'][] = array('url'=>$_SERVER['HTTP_REFERER'],'title'=>'固定传播基金管理列表');
        }
        $this->viewData['breadcrumb'][] = array('url'=>'','title'=>'固定传播基金申请查看');
        //载入模型
        $this->load->model('spreadProcessModel');
        $this->load->model('spreadProcStoreModel');
        $this->load->model('spreadProjectModel');
        //主线流程数据
        $procData = $this->spreadProcessModel->getNewData($procId);
        if (!$this->auth->isSpreadBudgetCheck($procData)){
            showError('您无权限查看');
        }
        $this->viewData['procData'] = $procData;
        //专营店数据
        $this->load->model('sellpointModel');
        $this->viewData['storeData'] = $this->sellpointModel->getStoreIdData($procData['storeId']);
        $procId = $procData['belongProcId'];
        //已选专营店列表
        $storeList = $this->spreadProcStoreModel->getList(array('procId'=>$procId));
        $this->viewData['storeList'] = $storeList;
        //投放类型列表
        $projectList = $this->spreadProjectModel->getNewList(array('procId'=>$procId));
        $this->viewData['projectList'] = $projectList;
        //项目合同总金额
        $projectSumMoney = $this->spreadProjectModel->getSum(array('procId'=>$procId),'applyMoney');
        $this->viewData['projectSumMoney'] = $projectSumMoney;
        //审核日志
        $this->load->model('auditLogModel');
        $this->viewData['auditList'] = $this->auditLogModel->getLogs(51, $procId);
        $this->viewData['auditData'] = $this->auditLogModel->getLastLog(51, $procId);
        //操作
        $this->viewData['action'] = 'check';
        
        $this->load->view('SpreadBudget/check', $this->viewData);
    }
}